package com.example.demo.utils;

import org.springframework.util.NumberUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @author cys1731 2020/4/26 16:03
 *
 * https://www.developers.pub/wiki/1002310/
 */
public class NumberUtil extends NumberUtils {

    public static float floatScale(float f) {
        return floatScale(f, 2);
    }

    public static float floatScale(float f, int scale) {
        BigDecimal bigDecimal = new BigDecimal(f);
        return bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    public static String scalePercentStr(float f) {
        DecimalFormat decimalFormat = new DecimalFormat("#.##%");
        return decimalFormat.format(f);
    }

    public static int floatToInt(float f) {
        BigDecimal bigDecimal = new BigDecimal(f);
        return bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
    }

    public static double floatToDoubleScale(float f) {
        BigDecimal bigDecimal = new BigDecimal(f);
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
